package com.dayu.finecomm.handler.tpacket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.encoder.PacketEncoder;
import com.dayu.finecomm.protocol.SpecialCareChannelInboundAdapter;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.source.ListenSource;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * @ClassName: TPacketCommitHandler
 * @Description:报文分发（当作为主服务器时，下发给连接上来的客户端）
 * @author: 戴卫国
 * @date: 2018年2月23日 下午4:03:25
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
public final class TPacketCommitHandler extends SpecialCareChannelInboundAdapter<TPacket> {

	final ListenSource source;

	static Logger LOGGER = LoggerFactory.getLogger(TPacketCommitHandler.class);

	public TPacketCommitHandler(ListenSource source) {

		this.source = source;
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, TPacket msg) throws Exception {

		// LOGGER.info("TPacketCommitHandler - channelRead0 - start");
		for (ChannelHandlerContext c : source.getListeners().values()) {

			for (ByteBuf buf : PacketEncoder.encode(msg, source.getListenType())) {
				c.writeAndFlush(buf);
			}
		}

		if (msg.command != null) {

			msg.command.station = msg.id();
			ctx.fireChannelRead(msg.command);
		}
		// 继续往下传
		ctx.fireChannelRead(msg);

		// LOGGER.info("TPacketCommitHandler - channelRead0 - end");
	}
}